package com.lagou.edu.wwyan.nacos.user.service.impl;

import com.lagou.edu.wwyan.nacos.user.dao.LagouTokenDao;
import com.lagou.edu.wwyan.nacos.user.dao.LagouUserDao;
import com.lagou.edu.wwyan.nacos.user.entity.LagouToken;
import com.lagou.edu.wwyan.nacos.user.entity.LagouUser;
import com.lagou.edu.wwyan.nacos.user.service.LagouUserService;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;
import java.util.UUID;

@Service
@DubboService
public class LagouUserServiceImpl implements LagouUserService {
    @Autowired
    private LagouUserDao userDao;
    @Autowired
    private LagouTokenDao tokenDao;
    @Override
    public Boolean isRegister(String email) {
        return userDao.getByEmail(email) != null;
    }

    @Override
    public Boolean register(String email, String password, String code) {
        LagouUser user = userDao.getByEmail(email);
        if (user != null){
            return false;
        }

        //todo 校验验证码
        user = new LagouUser();
        user.setEmail(email);
        user.setPassword(password);
        userDao.save(user);
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String login(String email, String password) {
        LagouUser user = userDao.getByEmail(email);
        if (user == null){
            return null;
        }
        if (!Objects.equals(password,user.getPassword())){
            return null;
        }
        //todo 保存token

        String token = UUID.randomUUID().toString();
        LagouToken lagouToken = new LagouToken();
        lagouToken.setEmail(email);
        lagouToken.setToken(token);
        tokenDao.save(lagouToken);
        return token;
    }
    @Override
    public LagouToken getLagouToken(String token){
        return tokenDao.getByToken(token);
    }
}
